package com.lijin.service.impl;

import com.lijin.dao.UserDao;
import com.lijin.dataobject.entity.User;
import com.lijin.service.UserService;
import com.lijin.utils.MD5Util;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * Created by gold-jx on 2017/6/2.
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public void register(User user) {
        try {
            log.info("开始注册....");
            //1.入参不能为空
            Assert.notNull(user,"用户入参不能为空!");
            //2.用户名不能为空
            Assert.notNull(user.getTbName(),"用户名不能为空!");
            //3.用户密码不能为空
            Assert.notNull(user.getTbPassword(),"用户密码不能为空!");
            //4.密码加密
            user.setTbPassword(MD5Util.getMD5to16(user.getTbPassword()));

            //5.增加
            int count=userDao.insertUser(user);
            if(count==1){
                log.info("结束注册....");
            }else{
                log.error("添加数据库失败!");
                Assert.isTrue(false,"添加数据库失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("注册失败", e);
        }
    }

    @Override
    public void deleteUser(String name) {
        try {
            //1.用户名不能为空
            Assert.notNull(name,"用户名不能为空");
            //2.删除
            int count=userDao.deleteUserByName(name);
            if(count !=1){
                Assert.isTrue(false,"用户民为: "+name+" 用户不存在");
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("根据用户名删除用户失败", e);
        }

    }

    @Override
    public void updateUser(User user) {
        try {
            //1.用户不能为空
            Assert.notNull(user,"用户入参不能为空!");
            //2.用户名不能为空
            Assert.notNull(user.getTbName(),"用户名不能为空");
            //3.修改
            int count=userDao.updateUserByName(user);
            if(count !=1){
                log.error("修改数据库失败!");
                Assert.isTrue(false,"修改数据库失败");
            }

        }catch (Exception e){
            e.printStackTrace();
            log.error("根据用户名修改用户失败", e);
        }


    }

    @Override
    public User findUserByName(String name) {
        //1.用户名不能为空
        Assert.notNull(name,"用户名不能为空");
        //2.查询
        User user=userDao.findUserByName(name);
        return user;
    }

    @Override
    public List<User> findUserAll() {
        List<User> userList=userDao.findUserAll();
        return userList;
    }
}

